package com.mars.basic.service;

import com.mars.basic.allmain.entity.AdminRoleEntity;
import com.mars.basic.allmain.po.QAdminRole;
import com.mars.basic.allmain.po.QAdminUser;
import com.mars.basic.allmain.po.QRole;
import com.mars.basic.allmain.po.Role;
import com.mars.basic.allmain.vo.AdminRoleVo;
import com.mars.basic.repository.AdminRoleRepository;
import com.mars.common.utils.DslUtils;
import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQuery;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AdminRoleService {

    final AdminRoleRepository userRepository;

    final RoleService roleService;

    final AdminUserService adminUserService;


    public AdminRoleRepository getAdminRoleRepository() {
        return userRepository;
    }


    public void addAdmin() {

    }

    public boolean check(AdminRoleVo vo) {
        boolean exists = getAdminRoleRepository().exists(QAdminRole.adminRole.roleId.eq(vo.getRoleId()).and(QAdminRole.adminRole.adminId.eq(vo.getAdminUserId())));
        return !exists;
    }

    /**
     * 获取该用户的所有角色
     *
     * @param id
     * @return
     */
    public List<Role> findRolesByAdminId(Integer id) {
        JPAQuery<Tuple> where = DslUtils.getJPAQueryFactory().select(QAdminUser.adminUser, QAdminRole.adminRole, QRole.role)
                .from(QAdminUser.adminUser)
                .leftJoin(QAdminRole.adminRole).on(QAdminRole.adminRole.adminId.eq(QAdminUser.adminUser.id))
                .leftJoin(QRole.role).on(QRole.role.id.eq(QAdminRole.adminRole.roleId))
                .where(QAdminUser.adminUser.id.eq(id));
        List<Role> roles = where.fetch().stream().map(o -> o.get(QRole.role)).collect(Collectors.toList());
        return roles;
    }

    /**
     * 获取该用户所关联角色的id
     * @param adminId
     * @return
     */
    public List<Integer> findRoleIdsByAdmin(Integer adminId) {
        List<AdminRoleEntity> adminRoleEntityList = getAdminRoleRepository().findAll(QAdminRole.adminRole.adminId.eq(adminId));
        List<Integer> roleIds = adminRoleEntityList.stream().mapToInt(AdminRoleEntity::getRoleId).boxed().collect(Collectors.toList());
        return roleIds;
    }

    /**
     * 根据用户获取关联信息
     * @param adminId
     * @return
     */
    public  List<AdminRoleEntity> findAdminRoleByAdminId(Integer adminId) {
        List<AdminRoleEntity> adminRoleEntityList = getAdminRoleRepository().findAll(QAdminRole.adminRole.adminId.eq(adminId));
        return adminRoleEntityList;
    }
}
